package twelfth.管道流;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

class Send implements Runnable{
    private PipedOutputStream pos=null;

    public Send() {
        this.pos=new PipedOutputStream();//实例化输出流
    }

    @Override
    public void run() {
        String s ="大张伟！";
        try {
            this.pos.write(s.getBytes());//输出信息
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            this.pos.close();       //关闭输出流
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public PipedOutputStream getPos() { //通过线程类得到输出流
        return pos;
    }
}
class Receive implements Runnable{
    private PipedInputStream pis = null;
    public Receive(){
        this.pis=new PipedInputStream();
    }

    @Override
    public void run() {
        byte[] b =new byte[1024];
        int len = 0;
        try {
            len=this.pis.read(b);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            this.pis.close();   //关闭输出流
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("接收的内容是："+new String(b,0,len));
    }

    public PipedInputStream getPis() {
        return pis;
    }
}
public class 验证管道流 {
    public static void main(String[] args) throws IOException {
        Send s = new Send();
        Receive r = new Receive();
        s.getPos().connect(r.getPis());//连接管道
        new Thread(s).start();//启动线程
        new Thread(r).start();//启动线程
    }
}
/**
 * 上面的程序定义了两个对象，在发送的线程类中定义了管道输出流，在接收的线程类中定义了管道的输出流，在操作的时候只需要使用PipedOutputStream类中
 * 提供的connection()方法，就可以将两个线程管道连接在一起
 */
/*
D:\WorkSpaces\Java\jdk-21\bin\java.exe "-javaagent:D:\Software\IntelliJ IDEA\IntelliJ IDEA 2023.3.2\lib\idea_rt.jar=65313:D:\Software\IntelliJ IDEA\IntelliJ IDEA 2023.3.2\bin" -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath D:\WorkSpaces\JavaDevelopBase_start_329\out\production\JavaDevelopBase_start_329 twelfth.管道流.验证管道流
接收的内容是：大张伟！

Process finished with exit code 0
 */